package com.xingzhe.pengji.security.services.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Service;

import com.xingzhe.pengji.security.dao.UserDao;
import com.xingzhe.pengji.security.domain.Authoritie;
import com.xingzhe.pengji.security.domain.User;
import com.xingzhe.pengji.security.services.AuthoritieService;
import com.xingzhe.pengji.security.services.UserService;

@Service("userService")
public class UserServiceImpl<T extends User> implements UserService<T>
{
    
    private static final Log log = LogFactory.getLog(UserServiceImpl.class);
    @Autowired
    private UserDao<T> userDao;
    
    @Autowired
    private AuthoritieService<Authoritie> authoritieService;
    
    @Override
    public void addUser(T t)
    {
        userDao.addUser(t);
    }
    
    @Override
    public void updateUser(T t)
    {
        this.userDao.updateUser(t);
    }
    
    @Override
    public User findUserById(String id)
    {
        return this.userDao.findUserById(id);
    }
    
    @Override
    public void delUser(T t)
    {
        this.userDao.delUser(t);
    }
    
    @Override
    public User getUserByName(String userName)
    {
        List<User> listUsers = this.userDao.findAuthByUserName(userName);
        User user = null;
        if (0 != listUsers.size())
        {
            user = listUsers.get(0);
        }
        return user;
    }
    
    @Override
    public List<GrantedAuthority> loadUserAuthoritiesByName(String userName)
    {
        try
        {
            List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
            @SuppressWarnings("unchecked")
            List<String> listAuthoritieName = (List<String>) authoritieService.getAllAuthoritieNameByUserName(userName);
            for (String authoritieName : listAuthoritieName)
            {
                SimpleGrantedAuthority a = new SimpleGrantedAuthority(authoritieName);
                auths.add(a);
            }
            return auths;
        }
        catch (RuntimeException e)
        {
            log.error("find by authorities by username failed.", e);
            throw e;
        }
    }
 
}
